frontend/pages/api/nauth/[...nextauth].js (view raw)
1import NextAuth from 'next-auth';
2import CredentialsProvider from 'next-auth/providers/credentials';
3import GoogleProvider from 'next-auth/providers/google';
4
5const {STRAPI_URL = 'http://localhost:1337'} = process.env;
6
7export default NextAuth({
8 providers: [
9 CredentialsProvider({
10 name: 'Strapi',
11 credentials: {
12 email: {label: 'Email', type: 'text'},
13 password: {label: 'Password', type: 'password'},
14 },
15 async authorize(credentials, req) {
16 try {
17 const response = await fetch(`${STRAPI_URL}/api/auth/local`, {
18 method: 'POST',
19 headers: {'Content-Type': 'application/json'},
20 body: JSON.stringify({
21 identifier: credentials.email,
22 password: credentials.password,
23 }),
24 });
25 const data = await response.json();
26 const {user, jwt} = data;
27 return {...user, jwt};
28 } catch (error) {
29 console.error({error});
30 return null;
31 }
32 },
33 }),
34 GoogleProvider({
35 clientId: process.env.GOOGLE_CLIENT_ID,
36 clientSecret: process.env.GOOGLE_CLIENT_SECRET,
37 }),
38 ],
39 session: {
40 jwt: true,
41 },
42 callbacks: {
43 jwt: async params => {
44 const {token, user, account} = params;
45
46 // Google Auth
47 if (account?.provider === 'google') {
48 const strapiUrl = process.env.STRAPI_URL || 'http://localhost:1337';
49 const response = await fetch(
50 `${strapiUrl}/api/auth/${account.provider}/callback?access_token=${account?.access_token}`
51 );
52 const data = await response.json();
53 token.id = data.user.id;
54 token.jwt = data.jwt;
55 token.email = data.user.email;
56 token.username = data.user.firstname;
57 token.lang = data.user.lang?.toLowerCase();
58 }
59
60 // Strapi Auth
61 else if (user) {
62 token.id = user.id;
63 token.jwt = user.jwt;
64 token.email = user.email;
65 token.username = user.firstname;
66 token.lang = user.lang?.toLowerCase();
67 }
68
69 return token;
70 },
71 session: async params => {
72 const {session, token} = params;
73 if (session) {
74 session.token = token;
75 session.user.name = token.username;
76 session.user.lang = token.lang;
77 }
78 return session;
79 },
80 },
81 pages: {
82 signIn: '/auth/login',
83 },
84});